﻿var CombinationGenerator = {};

CombinationGenerator.getArray = function (k, n) {

    var cacheKey = k + n * 10;
    if (CombinationGenerator.getArray.cache[cacheKey])
        return CombinationGenerator.getArray.cache[cacheKey];

    var total = Math.factorial(n) / (Math.factorial(k) * Math.factorial(n - k));
    var combinations = [];
    var lastCombination = [];

    for (var i = 0; i < k; i++) {
        lastCombination.push(i);
    }
    combinations.push(lastCombination);

    for (var rowNumber = 1; rowNumber < total; rowNumber++) {
        var i = k - 1;
        while (i > -1) {
            if (lastCombination[i] < (n - k + i)) {
                lastCombination = lastCombination.slice(0);
                lastCombination[i] = lastCombination[i] + 1;

                var j = i;
                while (j < k - 1) {
                    j++;
                    lastCombination[j] = lastCombination[j - 1] + 1;
                }
                combinations.push(lastCombination);
                break;
            }
            i--;
        }
    }

    CombinationGenerator.getArray.cache[cacheKey] = combinations;
    return combinations;
};

CombinationGenerator.getArray.cache = CombinationGenerator.getArray.cache || []